package com.gking.centerSystem.service.Sort;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.gking.centerSystem.common.ProgramException;
import com.gking.centerSystem.common.Result;
import com.gking.centerSystem.entity.Sort;
import com.gking.centerSystem.mapper.SortMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Slf4j
@Service
public class SortServiceImpl extends ServiceImpl<SortMapper, Sort> implements SortService {


    @Resource
    private SortMapper sortMapper;

    /**
     * 获取分类列表
     *
     * @return s
     */
    @Override
    public Result<List<Sort>> getSortList() {
        try {
            List<Sort> list = sortMapper.getAllSortList();
            return Result.success("获取分类成功", list);
        } catch (Exception e) {
            log.error("获取分类失败 {}", e.getMessage());
            throw new ProgramException();
        }
    }

    @Override
    public void createSystemDefaultSort(String description, String systemCode) {
        try {
            //为根系统创建分类
            Sort sort = new Sort();
            sort.setDescription(description);
            sort.setSystemCode(systemCode);
            sort.setLevel(1);
            sort.setWeight(0);
            sortMapper.insert(sort);

            // 默认创建的一些分类
            String id = sort.getId();
            Map<String, String> objectMap = new HashMap<>();
            objectMap.put("permission", "权限分类");
            objectMap.put("role", "角色分类");
            objectMap.put("page", "页面分类");
            for (Map.Entry<String, String> entry : objectMap.entrySet()) {
                Sort s = new Sort();
                s.setLevel(2);
                s.setParentId(id);
                s.setType(entry.getKey());
                s.setDescription(entry.getValue());
                s.setSystemCode(systemCode);
                sortMapper.insert(s);
            }
        } catch (Exception e) {
            log.error("创建默认分类失败 {}", e.getMessage());
            throw new ProgramException();
        }
    }

    /**
     * 创建子分类
     *
     * @param description 分类描述
     * @param parentId    父类id
     * @param weight      优先级，可选
     * @return s
     */
    @Transactional
    @Override
    public Result<String> createSort(String description, String parentId, Integer weight) {

        if (description.isEmpty() || parentId.isEmpty()) return Result.error("请将参数补充完整");
        if (weight != null && weight < 0) return Result.error("优先级数字最小为0");

        try {
            // 获取上级分类信息
            Sort parentSort = this.getById(parentId);
            if (parentSort == null) return Result.error("父类不存在");
            if (parentSort.getLevel() == 1) return Result.error("无法创建二级分类");

            // 设置分类层级，如何存在上级id，则通过计算上级id得出层级
            int level = parentSort.getLevel() + 1;

            Sort sort = new Sort();
            sort.setSystemCode(parentSort.getSystemCode());
            sort.setDescription(description);
            sort.setLevel(level);
            if (weight != null && weight > 0) sort.setWeight(weight);
            sort.setParentId(parentId);
            sort.setType(parentSort.getType());

            this.save(sort);

            return Result.success("创建分类成功");
        } catch (Exception e) {
            log.error("创建分类失败 {}", e.getMessage());
            throw new ProgramException();
        }
    }

    /**
     * 修改分类
     *
     * @param description 分类描述
     * @param sortId      分类id
     * @param weight      优先级，可选
     * @return s
     */
    @Override
    @Transactional
    public Result<String> updateSort(String description, String sortId, Integer weight) {

        if (description.isEmpty() || sortId.isEmpty()) return Result.error("请将参数补充完整");
        if (weight != null && weight < 0) return Result.error("优先级数字最小为0");

        try {

            Sort s = this.getById(sortId);
            if (s == null) return Result.error("分类不存在");
            if (s.getLevel() == 2) return Result.error("无法修改二级分类");


            Sort sort = new Sort();
            sort.setDescription(description);
            sort.setId(sortId);
            if (weight != null && weight > 0) sort.setWeight(weight);
            this.updateById(sort);
            return Result.success("修改分类成功");
        } catch (Exception e) {
            log.error("修改分类失败 {}", e.getMessage());
            throw new ProgramException();
        }
    }

    /**
     * 批量删除分类
     *
     * @param sortIdList 分类id列表
     * @return s
     */
    @Transactional
    @Override
    public Result<String> deleteSort(List<String> sortIdList) {
        if (sortIdList.isEmpty()) return Result.error("请选择要删除的分类");

        try {
            for (String sortId : sortIdList) {
                if (this.getById(sortId).getLevel() == 2) return Result.error("无法删除二级分类");

                LambdaQueryWrapper<Sort> queryWrapper = new LambdaQueryWrapper<>();
                queryWrapper.eq(Sort::getParentId, sortId);
                queryWrapper.eq(Sort::getIsDelete, 0);
                if (!this.list(queryWrapper).isEmpty()) return Result.error("存在子类，无法删除");

                LambdaUpdateWrapper<Sort> wrapper = new LambdaUpdateWrapper<>();
                wrapper.set(Sort::getIsDelete, 1);
                wrapper.eq(Sort::getId, sortId);
                wrapper.set(Sort::getDeleteTime, LocalDateTime.now());
                this.update(wrapper);
            }
            return Result.success("删除分类成功");
        } catch (Exception e) {
            log.error("删除分类失败 {}", e.getMessage());
            throw new ProgramException();
        }
    }
}
